/* 
 * File:   main.cpp
 * Author: 1
 *
 * Created on 28 марта 2015 г., 18:32
 */

#include <cstdlib>
#include <stdio.h>
#include <iostream>

#include <dirent.h>
#include <sys/stat.h>
#include <cerrno>
#include <string.h>


using namespace std;

/*int direntcmp(dirent* d1, dirent* d2) {
    return strcmp(d1->d_name, d2->d_name);
}*/
int sel(const dirent* d) {
    if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) return 0;
    return 1;
}
/*
 */
void drawTree(char* path, char* pref) {
    DIR* dir = opendir(path);
    if (!dir) {
        perror("opendir");
        printf("%s", path);
        //exit(errno);
    };  
    dirent **entries;
    int n = scandir(path, &entries, sel, alphasort);
    int foldLast = -1;
    for (int i = 0; i < n; i++) {
        struct stat st;
        char filename[512];
        snprintf(filename, sizeof(filename), "%s/%s", path, entries[i]->d_name);
        lstat(filename, &st);
        if (!S_ISDIR(st.st_mode)) {
            printf("%s", pref);
            if (i != n - 1 || foldLast != -1) {
                printf("├──");
            } else {
                printf("└──");
            }
            puts(entries[i]->d_name);
        } else {
            foldLast = i;
        }
    }
    char* newPref = new char[strlen(pref) + 9]; //Создаем новый префикс
    strcpy(newPref, pref);
    strcat(newPref, "│  ");
    for (int i = 0; i < n; i++) {
        struct stat st;
        char filename[512];
        snprintf(filename, sizeof(filename), "%s/%s", path, entries[i]->d_name);
        lstat(filename, &st);
        if (S_ISDIR(st.st_mode)) {
            printf("%s", pref);            
            if (i != foldLast) {
                printf("├──");
            } else {
                strcpy(newPref, pref);
                newPref[strlen(pref)] = '\0';
                strcat(newPref, "   "); 
                printf("└──");
            }
            puts(entries[i]->d_name);
            drawTree(filename, newPref);
        }
    }
    delete[] newPref;
    
    //char *files[] = new char*[n];
    //char *folders[] = new char*[n];
    
    /*while ((entry = readdir(dir)) != NULL) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
        for (int i = 0; i < tabs; i++) {
            printf("   ");
        }
        printf("|---");
        puts(entry->d_name);
    
        struct stat st;
        char filename[512];
        snprintf(filename, sizeof(filename), "%s/%s", path, entry->d_name);
        lstat(filename, &st);
        if (S_ISDIR(st.st_mode)) {
            drawTree(filename, tabs + 1); 
        } else {
            files[] =             
        }
    }   */
   
    closedir(dir);
}

/*
 * 
 */
int main(int argc, char** argv) {
    char* path = argv[1];
    //puts(getcwd());
    drawTree(path, "");
    return 0;
}

